//<![CDATA[

//var auth = AjaxLib();

var ii = 0;
// 接口返回的字符串
var responsetext;


var elementss;
var mtitle;
var stopover_time = 10;
var points = new Array;
var select_state = "all";
var old_select_state = "-1";
var point_state = "green";
var _interval;

// 标志数组
var markers = new Array;
var nowicon = gray_icon;
var maxspeed = 0;
// 构建图标
var map;
var mapControl1;
var geocoder;
var showingOptIndex = -1;

var icon = new GIcon();
var red_icon = getIcon("red");// new GIcon();
var gray_icon = getIcon("gray");// new GIcon();
var green_icon = getIcon("green");// new GIcon();
var yellow_icon = getIcon("yellow");// new GIcon();
var white_icon = getIcon("white");// new GIcon();

var reTryCount = 0;
var objectLen = 0;

var mapType = "";

var index = "index";

function setIndex(ind){
	index = ind;
}



function getdata() {
	var myAjax = new Ajax.Request(
			"GetLocationInfo",
			{
				method :"post", // 表单提交方式
				parameters :"mapType=" + mapType, // 提交的表单数据
				onComplete : function(x) { // 提交成功回调
					var reponseStr = x.responseText;
					// alert(reponseStr);

					var reponseStrArr = reponseStr.split("|");
					responsetext = reponseStrArr[1];

					if (responsetext == null) {// 如果新企业用户第一次登录
						window.clearInterval(intervalID);
						alert("您名下还没有上线的车辆!");
						return;
					}

					elementss = responsetext.split(";");
					// alert("gkhg");
					if (objectLen == 0) {
						objectLen = elementss.length;
					}
					if (objectLen != elementss.length) {
						// 有新目标加入，请重新登录
						window.clearInterval(intervalID);// document.execCommand('Refresh')
						// document.write("<a href='#'
						// onClick=\"javascript:top.location.replace('index.jsp');return
						// false;\">目标有变动，请重新登录....</a>");
						alert("目标有变动，需要刷新...." + intervalID);
						
						document
								.write("<script type=\"text/javascript\">window.parent.location.reload();<\/script>");
						/*
												document
						.write("<script type=\"text/javascript\">window.parent.leftFrame.location.reload();<\/script>");
						*/
						alert("ddd");
						return;
					}
					serverTime = reponseStrArr[0];
					reTryCount = 0;

					// 初始化
					if (intervalID == "-1") {
						// alert("sdfjksdfl;");
						cars();
						// 默认显示在线的
						try {

							parent.leftFrame.document
									.getElementsByName('car_state')[1].click();

						} catch (e) {
						}

					}
					// 正常循环
					else {
						chkcars();
						parent.leftFrame.window.modifyState(points);
					}

				},
				onError : function(x) { // 提交失败回调
					if (reTryCount == 4) {
						// alert("3333"+reTryCount);
						window.clearInterval(intervalID);
						// if(auth.status !=
						// 200){
						document
								.write("<a href='#' onClick=\"javascript:top.location.replace('"+index+".jsp?command=logout');return false;\">请重新登录....</a>");
						// } //
						// JavaScript代码段
						// alert(e);
						return;
					}
					// if(reTryCount < 3){
					// alert("1111"+reTryCount);
					reTryCount++;
					// setTimeout(getdata(), 2000);

				}
			});
}

var initMTitle = "名称：。。。。。。。。。<br>";
initMTitle += "状态：。。。。。。。。。<br>";
initMTitle += "时长：。。。。。。。。。<br>";
initMTitle += "信号：。。。。。。。。。";

// 从数组中取数，并生成一个点
// var container = parent.document.getElementById("contain");
function getpoint(number) {
	points[number] = elementss[number].split(",");
	// var stopover_time = getTimeDiff(serverTime, points[number][3]);
	// GPS_one中数据更新的最后时间 和 服务器时间之差。
	// var heart_time = getTimeDiff(serverTime, points[number][9]);
	// 心跳时间和服务器时间之差，算离线用
	if (points[number][10] == "2009-05-08 16:20:52")// 处理没有心跳数据的tracker
		points[number][10] = points[number][3];
	var heart_time = getTimeDiff(serverTime, points[number][10]);

	// 最新定位时间(sys_time)(?还是算服务器时间合适？在补传数据的时候会有何命门和服务器差好几分钟，却显示正常行驶状态)和最后一次移动定位时间之差，算静止时间()。
	var stopover_time = getTimeDiff(serverTime, points[number][3]);
	// var stopover_time = getTimeDiff(points[number][9], points[number][3]);

	// 定位时间和服务器时间之差，如果小于心跳时间，心跳时间重置
	var dingwei_time = getTimeDiff(serverTime, points[number][9]);
	if (dingwei_time < heart_time)
		heart_time = dingwei_time;
	else
		points[number][9] = points[number][10];

	point_state = getState(heart_time, points[number][4], stopover_time);

	mtitle = "名称：" + points[number][0] + "<br>";
	mtitle += "状态：" + getStateInText(point_state, points[number][4]) + "<br>";

	var showTime = points[number][9];
	//var showTime = points[number][10].substring(0,
										// points[number][9].length - 2);

	if (point_state == "white") {
		// mtitle += "时长："+exchange_time(stopover_time)+"<br>信号："+showTime;
		mtitle += "时长：" + exchange_time(heart_time) + "<br>信号：" + showTime;
		icon = white_icon;
		points[number][8] = point_state;
		return;
	}
	if (point_state == "gray") {
		
		var stopDesc = "";
		//if(stopover_time > 179)
			stopDesc = "时长："+ exchange_time(stopover_time) +"<br>";
		mtitle += stopDesc + "信号：" + showTime;
		icon = gray_icon;
		points[number][8] = point_state;
		return;
	}

	mtitle += "时速：" + points[number][4] + "Km/h-"
			+ getHangXiang(points[number][7], points[number][4]) + "<br>信息："
			+ showTime;
	if (points[number][4] < 80) {
		// 30秒内有数据正常，行使中
		icon = green_icon;
		points[number][8] = point_state;

		return;
	}
	if (120 > points[number][4] && points[number][4] >= 80) {
		// 黄灯，超速
		icon = yellow_icon;
		points[number][8] = point_state;

		return;
	}

	// 亮红,严重超速
	icon = red_icon;
	points[number][8] = point_state;
	// MM_controlSound('play', 'document.MM_120chaosu');
	// container.innerHTML += "<li><strong>"+ points[number][0] +" 严重超速一次("+new
	// Date().toLocaleString()+")</strong></li>";

}

// 判断多选一按钮
function chk() {
	// var obj = document.getElementsByName('car_state');
	var obj = parent.leftFrame.document.getElementsByName('car_state');
	for (i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			old_select_state = select_state;
			select_state = obj[i].value;
			// alert(select_state);
			// cars();
			chkcars()
			return;
		}

	}
	alert('你没选');
}

function chkcars() {
	// clearOverlaysAndListeners();
	// map.clearOverlays();

	// 如果地图的缩放比例大于10，目标居中...
	
	/*
	if (map.getZoom() > 13 && showingOptIndex != -1) {
		map.setCenter(new GLatLng(Number(points[showingOptIndex][2]),
				Number(points[showingOptIndex][1])));
	}
	*/

	for (i = 0; i < (elementss.length - 1); i++) {
		// 显示一个GPS目标
		getpoint(i);
		// 先隐藏
		markers[i].hide();

		// 根据需要再重新显示
		marke(i);
	}

	hideAllOpts();
	if (showingOptIndex != -1){
		markers[showingOptIndex].showPopup();
//		if(!map.getBounds().containsLatLng(new GLatLng(Number(points[showingOptIndex][2]), Number(points[showingOptIndex][1]))))
//			map.panTo(new GLatLng(Number(points[showingOptIndex][2]), Number(points[showingOptIndex][1])));

	}

}

// //-----cars
// 初始过程

var intervalID = "-1";
var zoomLinstener;
var initRoom, initCenter;
// var maptypechanged = false;

function cars() {
	if (intervalID != "-1")
		window.clearInterval(intervalID);

	var arr = getCenterPoint(elementss);
	// alert("arr=" + arr);
	var room = getRoom(arr[2]);
	initRoom = room;
	// alert("room="+room);
	initCenter = new GLatLng(arr[1], arr[0]);

	map.setCenter(initCenter, room);

	// map.clearOverlays();
	clearOverlaysAndListeners();
	for (i = 0; i < (elementss.length - 1); i++) {
		// 显示一个GPS目标
		getpoint(i);
		marke(i);
	}

	// 添加缩放完毕时间监听，隐藏所有options，重新过滤显示目标
	zoomLinstener = GEvent.addListener(map, "zoomend", function() {
		hideAllOpts();
		chkcars();
	});
	GEvent
			.addListener(map,
					"maptypechanged",
					function() {
						// alert("sfdsf");
					mapType = (map.getCurrentMapType().getName() == "卫星") ? "G_SATELLITE_MAP"
							: "";
					hideAllOpts();
					getdata();
					// alert("sfdsf");
					// chkcars();
				});

	try {

		parent.leftFrame.window.modifyState(points);

	} catch (e) {
		alert("欢迎进入全球定位监控后台！");
		try {
			parent.leftFrame.window.modifyState(points);
		} catch (e) {
		}
	}
	intervalID = window.setInterval( function() {

		nowicon = gray_icon;
		maxspeed = 0;
		getdata();

	}, 15000);

}

var overListeners = new Array();
var outLinstener = new Array();
var dbClickLinstener = new Array();

function move(i) {

	document.getElementById("markerText" + i).innerHTML = "<span id='markerText"
			+ i + "'><font size='2'>" + mtitle + "</font></span>"
	var newPoint = new GLatLng(Number(points[i][2]), Number(points[i][1]));
	markers[i].setLatLng(newPoint);

	markers[i].setImage(icon.image);
	/*
	 * //if(i != showingOptIndex) markers[i].hidePopup();
	 * 
	 * if(i == showingOptIndex){ markers[i].showPopup(); }
	 */
}

function showSelectedObject(i) {
	 //alert(i);
	if (map.getZoom() > initRoom){
//		map.panTo(new GLatLng(Number(points[i][2]), Number(points[i][1])));
		map.setCenter(new GLatLng(Number(points[i][2]), Number(points[i][1])));
//		alert(map.getCurrentMapType() + map.getZoom());
//	map.setCenter(new GLatLng(Number(points[i][2]), Number(points[i][1])), 
//			map.getZoom(), map.getCurrentMapType());
	
	}

//		if(!map.getBounds().containsLatLng(new GLatLng(Number(points[i][2]), Number(points[i][1]))))
//			map.panTo(new GLatLng(Number(points[i][2]), Number(points[i][1])));
	
	hideAllOpts();
	markers[i].showPopup();
	showingOptIndex = i;
}

function hideAllOpts() {
	for ( var j = markers.length - 1; j >= 0; j--) {
		markers[j].hidePopup();
	}
	// if(showingOptIndex != -1)
	// markers[showingOptIndex] = showPopup();
}

function drawMarker(i) {

	var opts = {
		text :"<span id='markerText" + i + "'><font size='2'>" + initMTitle
				+ "</font></span>",
		icon :icon
	};
	// optss[i] = opts;
	var marker = new PopupMarker(new GLatLng(Number(points[i][2]),
			Number(points[i][1])), opts);
	// var marker = new GMarker(new GLatLng(Number(points[i][2]),
	// Number(points[i][1])), {draggable:
	// false,icon:icon,title:mtitle});
	overListeners.push(GEvent.addListener(marker, "mouseover", function() {
		// if(showingOptIndex != -1)
			// markers[showingOptIndex].hidePopup();
			marker.showPopup();
			// showingOptIndex = -1;
		}));
	outLinstener.push(GEvent.addListener(marker, "mouseout", function() {
		marker.hidePopup();
	}));
	dbClickLinstener.push(GEvent.addListener(marker, "dblclick", function() {
		showObject(points[i][0]);
	}));

	markers[i] = marker;
	map.addOverlay(markers[i]);
	document.getElementById("markerText" + i).innerHTML = "<span id='markerText"
			+ i + "'><font size='2'>" + mtitle + "</font></span>"

	// map.addOverlay(marker);
	markers[i].hidePopup();
}

function clearOverlaysAndListeners() {
	if (intervalID == "-1")
		return;
	map.clearOverlays();
	for ( var j = overListeners.length - 1; j >= 0; j--) {
		GEvent.removeListener(overListeners[j]);
		GEvent.removeListener(outLinstener[j]);
		// GEvent.removeListener(zoomLinstener[j]);
	}
	GEvent.removeListener(zoomLinstener);

}

function marke(i) {
	if (select_state == "all") {
		if (intervalID != "-1")
			move(i);
		else
			drawMarker(i);
		return;
	}
	if (select_state == "white") {
		if (point_state == "white") {
			if (intervalID != "-1")
				move(i);
			else
				drawMarker(i);
		} else {
			move(i);
			markers[i].hide();
		}
		return;
	}

	if (select_state == "online") {
		// alert("1"+select_state);
		if (point_state != "white") {
			// alert("2"+point_state);
			if (intervalID != "-1")
				move(i);
			else
				drawMarker(i);
		} else {
			move(i);
			markers[i].hide();
		}
		return;
	}

}




var iconAddr = getIcon("center");
var marker = null;// new GMarker(point, iconAddr);
// iconAddr.image = "images/center.gif";

function showAddress(address) {
// alert(address);
	      if (geocoder) {
	        geocoder.getLatLng(
	          address,
	          function(point) {
	            if (!point) {
	              alert("不能解析: " + address);
	            } else {
	            	showingOptIndex = -1;//不让地图跟着选中目标跑
	              map.setCenter(point, 12);
	              hideAllOpts();
	              chkcars();
	              if(marker == null){
	            	  marker = new GMarker(point, iconAddr);
	            	  map.addOverlay(marker);
	              }
	              else
 	              marker.setLatLng(point);

	              marker.show(); 
	              
	              setTimeout(function(){marker.hide();}, 5000)  	          	              
	            }
	          }
	        );
	      }
	    }

	function showObject(object){
   	for(var i = 0; i < points.length; i ++){
			if(object == points[i][0]){
				map.setCenter(new GLatLng(Number(points[i][2]), Number(points[i][1])), 12);
				hideAllOpts();
				//markers[i].showPopup(); 
				showingOptIndex = i;
				chkcars();
				return;
			}
     }
     alert("没有查询到目标：" + object);
	}

	// var initRoom,initCenter;
	function gotoInitState(){
		map.setCenter(initCenter, initRoom);
		hideAllOpts();
	}